<template>
  <!-- 添加或修改销售信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="开票附件及备注信息填写" name="first">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="开票明细" prop="files">
                <file-upload :limit="100" v-model="form.files"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-form :inline="true" :model="queryParams" label-width="98px" ref="queryForm" size="small" v-show="showSearch">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="搜索条件" name="first">
          <el-form-item label="框架编号" prop="companyName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入框架编号"
                      v-model="queryParams.projectCode"/>
          </el-form-item>
          <el-form-item label="订单编号" prop="code">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入订单编号" v-model="queryParams.code"/>
          </el-form-item>
          <el-form-item label="买方" prop="customName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入买方"
                      v-model="queryParams.customName"/>
          </el-form-item>
          <el-form-item label="项目单位" prop="companyName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入项目单位"
                      v-model="queryParams.companyName"/>
          </el-form-item>
          <el-form-item label="制单人" prop="createName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入制单人"
                      v-model="queryParams.createName"/>
          </el-form-item>
          <el-form-item label="业务员" prop="salesmanName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入业务员"
                      v-model="queryParams.salesmanName"/>
          </el-form-item>
          <el-form-item label="下单日期" prop="orderDate">
            <el-date-picker clearable v-model="queryParams.orderDate" type="date" value-format="yyyy-MM-dd" size="mini"
                            placeholder="请选择下单日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="订单信息备注" prop="information">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入订单信息备注"
                      v-model="queryParams.information"/>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery" icon="el-icon-search" size="mini" type="primary">搜索</el-button>
            <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-table border v-loading="loading" ref="dragTable" :data="columns" row-key="id"
              @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column label="框架编号" align="center" prop="projectCode"/>
      <el-table-column label="订单编号" align="center" prop="code"/>
      <el-table-column label="买方(开票单位)" align="center" prop="customName"/>
      <el-table-column label="开票单位编码" align="center" prop="taxcode"/>
      <el-table-column label="开票金额" align="center" prop="taxAmount" width="300">
        <template slot-scope="scope">
          <el-input-number size="mini" v-model="scope.row.taxAmount" :precision="5" :min="0" width="300"
                           :max="scope.row.taxRemain"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="剩余开票" align="center" prop="taxRemain" />
      <el-table-column label="工程名称" align="center" prop="gongchengName" width="200">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.gongchengName"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="下单日期" align="center" prop="orderDate"/>
      <el-table-column label="项目单位" align="center" prop="companyName" show-overflow-tooltip/>
      <el-table-column label="制单人" align="center" prop="createName" show-overflow-tooltip/>
      <el-table-column label="业务员" align="center" prop="salesmanName" show-overflow-tooltip/>
      <el-table-column label="地区" align="center" prop="area">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_area" :value="scope.row.area"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="information" show-overflow-tooltip/>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <goods-sale-list-select-for-invoice ref="GoodsSaleListSelectForInvoice"
                                        @ok="updateOrderList"></goods-sale-list-select-for-invoice>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>


<script>
import {
  addAction,
  getAction,
  getById,
  deleteAction,
  updateAction
} from '@/api/manage'
import {
  updateGoodsSale
} from '@/api/develop/goodsInvoiceBatch'
import request from '@/utils/request'
import GoodsSaleListSelectForInvoice from "../../goodsSale/GoodsSaleListSelectForInvoice";

export default {
  name: "GoodsInvoiceBatchAll",
  components: {
    GoodsSaleListSelectForInvoice
  },
  dicts: ['company', 'goods_supplier', 'goods_customer', 'order_area'],
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "批量开票查看",
      // 是否显示弹出层
      open: false,
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      form: {},
      columns: [],
      customerId: "",
      total: 0,
      ids: "",
      selectIds: "",
      selectIdsNew: [],
      selectRows: [],
      // 表单校验
      rules: {
        projectId: [{required: true, message: "请选择项目信息", trigger: "blur"}],
        customerId: [{required: true, message: "请选择客户信息", trigger: "blur"}],
        invoiceCompany: [{required: true, message: "乙方项不能为空", trigger: "blur"}],
      },
      queryParams: {
        id: null,
        yearStr: null,
        pageNum: 1,
        pageSize: 20,
        name: null,
        code: null,
        master: null,
        customId: null,
        customName: null,
        companyName: null,
        contractDate: null,
        contractMoney: null,
        salesman: null,
        auditMoney: null,
        checkDate: null,
        checkState: null,
        fundCallback: null,
        information: null,
        createName: null,
        salesmanName: null,
        orderByColumn: "create_time",
        isAsc: "desc",
        params: {
          taxStatus: "0,1"
        },
      },
      url: {
        listProject: '/projectBaseInfo/projectBaseInfo/listNotAllKp',
        proNames: '/projectBaseInfo/projectBaseInfo/prjNames',
        insertBatch: '/goodsInvoice/goodsInvoice/insertBatch',
      },
      orderInfo: {},
      proNameOptions: [],
    };
  },
  created() {
  },
  methods: {

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.params = {}
      this.resetForm("queryForm");
      this.handleQuery();
    },
    showAddInvoiceAll() {
      this.reset();
      this.selectIds = "";
      this.open = true;
      this.loading = false;
      this.getList();
    },
    getList() {
      this.loading = true;
      getAction(this.url.listProject, this.queryParams).then(response => {
        this.columns = response.rows;
        for (let i = 0; i < this.columns.length; i++) {
          this.columns[i].taxAmount = this.columns[i].taxRemain;
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    handleRemove(row) {
      let that = this;
      that.columns = that.columns.filter((item) => {
        return item.id != row.id
      });
      that.form.columns = that.columns;
      that.selectIdsNew = [];
      for (let i = 0; i < that.columns.length; i++) {
        let row = that.columns[i];
        that.selectIdsNew.push(row.id);
      }
      that.selectIds = that.selectIdsNew;
      that.$modal.msgSuccess("移除成功！");
    },
    updateOrderList(selectRows) {
      let that = this;
      for (let i = 0; i < selectRows.length; i++) {
        let row = selectRows[i];
        that.columns.push(row);
      }
      var totalPrice = 0;
      for (let i = 0; i < that.columns.length; i++) {
        let row = that.columns[i];
        that.selectIdsNew.push(row.id);
        totalPrice += row.goodsTotalPrice;
      }
      that.form.amount = totalPrice;
      that.selectIds = that.selectIdsNew;
    },
    handleAddList() {
      let that = this;
      that.$refs.GoodsSaleListSelectForInvoice.showSelectSaleDialog(that.selectIds, that.form.customerId);
    },
    selectCustomer(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectCustomer;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.customerName = arr[i].label;
          }
        }
      })
    },
    selectSupplier(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectSsupplier;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.supplierName = arr[i].label;
          }
        }
      })
    },
    selectUser(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectUser;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.drawerName = arr[i].label;
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsId: null,
        goodsName: null,
        goodsBrand: null,
        goodsUnitPrice: null,
        goodsCount: null,
        goodsTotalPrice: null,
        saleDate: null,
        supplierId: null,
        supplierName: null,
        customerId: null,
        customerName: null,
        invoiceCompany: "1",
        invoice: "0",
        invoiceId: null,
        invoiceNo: null,
        status: "wkp",
        fundCallback: "whx",
        receipt: null,
        saleId: null,
        saleName: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId: this.$store.getters.deptId,
        deptName: this.$store.getters.deptName,
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectRows = selection;

    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      // 遍历 selectRows 如果开票金额是0
      if (that.selectRows.length == 0) {
        that.$modal.msgError("请选择开票订单");
        return;
      }
      for (let i = 0; i < that.selectRows.length; i++) {
        let row = that.selectRows[i];
        if (row.taxAmount == 0) {
          that.$modal.msgError("订单号"+row.code+",开票金额不能为0");
          return;
        }
      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          const forms = that.form;
          const proForm = Object.assign({}, forms);
          proForm.columns = that.selectRows;
          addAction(that.url.insertBatch, proForm).then(response => {
            that.$modal.msgSuccess("申请完成！");
            that.open = false;
            that.$emit('ok');
          });
        }
      });
    },
  }
};
</script>
